<template>
  <div class="cart">
    <el-table :data="cartStore.items" style="width: 100%">
      <el-table-column label="商品图片">
        <template #default="{ row }">
          <img :src="row.imageUrl[0]" alt="商品图片" class="cart-image" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column label="数量">
        <template #default="{ row }">
          <el-input-number v-model="row.quantity" :min="1" @change="() => updateQuantity(row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="() => removeItem(row.id)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="total-price">
      总价：{{ cartStore.totalPrice.toFixed(2) }}
    </div>
    <el-button type="primary" class="checkout-button" @click="checkout">结账</el-button>
  </div>
</template>

<script setup>
import { useCartStore } from '../stores/cartStore';
import { ref } from 'vue';
import axios from 'axios';

const cartStore = useCartStore();

const updateQuantity = (item) => {
  // 更新商品数量
  if (item.quantity <= 0) {
    cartStore.removeItem(item.id);
  } else {
    cartStore.updateItemQuantity(item.id, item.quantity);
  }
};

const removeItem = (id) => {
  // 移除商品
  cartStore.removeItem(id);
};

const checkout = async () => {
  // 结账逻辑：将购物车中的所有商品创建一个订单
  const orderItems = cartStore.items.map(item => ({
    productId: item.id,
    productName: item.name,
    price: item.price,
    quantity: item.quantity,
    orderDate: new Date().toISOString()
  }));

  alert("订单已创建成功");

  try {
    // 对每个商品单独进行 axios 请求，插入订单信息到数据库
    const promises = orderItems.map(async (item) => {
      const response = await axios.post('http://localhost:8080/api/order/createOrder', item);
    });
    // 等待所有请求完成
    await Promise.all(promises);
    console.log("所有商品订单已成功插入数据库");
  } catch (error) {
    console.error("插入订单时出错:", error);
    alert("插入订单时出错，请查看控制台获取详细信息");
  }

  // 清空购物车
  cartStore.clearCart();
};
</script>

<style>
.cart {
  margin: 20px;
}

.total-price {
  margin-top: 20px;
  text-align: right;
  font-size: 1.2em;
  font-weight: bold;
}

.cart-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 5px;
}

.checkout-button {
  margin-top: 20px;
  display: block;
  margin-left: auto;
  margin-right: 0;
}
</style>
